<?php
namespace app\task\model;

use app\common\model\Record as RecordModel;
use think\facade\Db;
use think\facade\Cache;

/**
 * 交易记录模型
 */
class Record extends RecordModel
{
    /**
     * 待支付订单详情
     */
    public function payDetail(string $order_no)
    {
        return Cache::get($order_no);
    }

    /**
     * 更新付款状态
     */
    public function updatePayStatus(string $transaction_id, array $data)
    {
        $gift_money = 0;//赠送金额
        $coupon = [];//赠送优惠券
        if(isset($data['recharge_plan_id']) AND $data['recharge_plan_id'] > 0){
            if($plan = RechargePlan::detail($data['recharge_plan_id'])){
                if($plan['gift_type']['value'] == 10){
                    //优惠券
                    for($n=0;$n<$plan['gift_money'];$n++){
                        //计算优惠券到期时间
                        switch ($plan['coupon']['valid_time']['value']) {
                            case '10':
                                $expiretime = strtotime(date('Y-m-d').'23:59:59');
                                break;
                            case '20':
                                $expiretime = strtotime("+1 week");
                                break;
                            case '30':
                                $expiretime = strtotime("+1 month");
                                break;
                            case '40':
                                $expiretime = strtotime("+1 year");
                                break;
                            default:
                                $expiretime = time();
                                break;
                        }
                        $coupon[] = [
                            'coupon_id' => $plan['coupon']['coupon_id'],
                            'type' => $plan['coupon']['type']['value'],
                            'rule' => $plan['coupon']['rule']['value'],
                            'expiretime' => $expiretime,
                            'shop_id' => $data['shop_id'],
                            'user_id' => $data['user_id'],
                            'applet_id' => $data['applet_id']
                        ];
                    }
                }else{
                    $gift_money = $plan['gift_money']; //赠送现金余额
                }
            }
        }
    	// 开启事务
        Db::startTrans();
        try {
            //更新用户余额信息
			$user = User::getUser(['user_id' => $data['user_id']]);
			$user->money = ['inc', $data['money']+$gift_money];//增加充值金额
			$user->score = ['inc', $data['money']];//增加
			$user->save();
            //是否赠送优惠券
            if(sizeof($coupon) > 0){
                $model = new CouponUser;
                $model->saveAll($coupon);
            }
			$data['transaction_id'] = $transaction_id;
			$this->save($data);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
